<?php

// Include config file
include('./common.php');

// Connect to database
$link = dbConnect();

//make sure that the page and threadID are set
if (!isset($_POST['page']) || empty($_POST['page'])) {
    $page = 1;
}else{
	$page = mysql_real_escape_string($_POST['page']);
}

//if we don't have a threadID, throw them home
if (!isset($_POST['threadID'])) {
	echo "output=threadNotSet";
	return;
}else{
	$threadID = mysql_real_escape_string($_POST['threadID']);
}

//clean up flash stuff
$postsPerPage = mysql_real_escape_string($_POST['postsPerPage']);
$webImgDir = $_POST['webImgDir'];
$abImgDir = $_POST['abImgDir'];
$avatarDir = $_POST['avatarDir'];
$guestGroupID = mysql_real_escape_string($_POST['guestGroupID']);

//only grab the posts per page amount
$offset = ($page - 1) * $postsPerPage;

//get the name of the forum, forumID and thread name for breadcrumbs and permission check
$breadResult = mysql_query("SELECT t.topic, t.displayOrder, t.readMode, f.forumID, f.title 
						   FROM ".TABLE_PREFIX."_forums f, ".TABLE_PREFIX."_threads t 
						   WHERE t.forumID = f.forumID 
						   AND t.threadID = ".$threadID);

//make sure that we have a thread!
if(mysql_num_rows($breadResult) == 0){
	echo "output=threadNotFound";
	mysql_close($link);
	return;
}

$data = mysql_fetch_object($breadResult);

//if they can't view this forum then don't bother going on
if(isset($_POST['username'])){
	//get the userID from the login data
	$user = auth($_POST['username'], $_POST['password']);
	if($user == ""){
		echo "output=badLogin";
		return;
	}
	
	//setup a userID for the rest of the script
	$flashUserID = $user['id'];
}else{
	$flashUserID = -1;
}

//get the user's permissions for this forum
$perms = checkForumPermissions($data->forumID, $flashUserID, $guestGroupID);

if(!$perms){
	echo "output=permissionError";
	mysql_close($link);
	return;
}

//let flash know about the user's perms
$output = $perms;

//if we can go on, send the breadcrumb data to flash
$output .= "&threadTopic=".urlencode(stripslashes($data->topic))."&threadDisplayOrder=".$data->displayOrder."&threadReadMode=".$data->readMode."&forumID=".$data->forumID."&forumTitle=".urlencode(stripslashes($data->title));


// Build query to fetch thread
$result = mysql_query("SELECT SQL_CALC_FOUND_ROWS p.*, u.*
						FROM ".TABLE_PREFIX."_posts p, ".TABLE_PREFIX."_users u
						WHERE p.threadID = ".$threadID."
						AND p.userID = u.userID
						ORDER BY p.posted ASC 
						LIMIT $offset,$postsPerPage");

if (!$result) {
    fail("mySqlError");
}

//set up a quick query to get the total number of posts to send to flash
$totalResult = mysql_query("SELECT FOUND_ROWS() AS postTotal");
$dataTotal = mysql_fetch_object($totalResult);
$pages = ceil($dataTotal->postTotal / $postsPerPage);
$output .= "&currentPage=$page&totalPages=$pages";

// Find out how many posts in this thread
$postCount = mysql_num_rows($result);

// Setup our variable to hold output
$output .= "&postCount=$postCount&threadID=$threadID";

// For each post returned...
for ($i = 0; $i < $postCount; $i++) {
    // Extract post details from database
    $post = mysql_fetch_object($result);
    
	//used for editing messages
    $postID = $post->postID;
    $userID = $post->userID;
	
	$message = htmlspecialchars(stripslashes($post->message));
	$emoticons = $post->emoticons;
    $posted = timeParse($post->posted);
	
	//if it's the last post and we are logged in, track the last read post
	if($i == $postCount - 1){
		//track the last post in this thread to the user
		if(isset($flashUserID)){
			trackThread($flashUserID, $data->forumID, $threadID, $post->posted);
		}
	}
	
	//get the breakdown of post details
    $username = stripslashes($post->username);
    $userTitle = stripslashes($post->title);
    $location = stripslashes($post->location);
    $homepage = stripslashes($post->homepage);
    $email = stripslashes($post->email);
    $signature = stripslashes($post->signature);
	$avatarURL = stripslashes($post->avatarURL);
    $posts = number_format($post->posts);
	$joined = strftime("%b %d, %Y", $post->joined);
	
	//check to see if the avatarURL is a local image or extneral (legacy support for now)
	if(substr($avatarURL, 0, 4) != "http" && $avatarURL != ""){
		//means it's local, so slap the install dir on this bad boy
		$avatarURL = $avatarDir.$avatarURL;
	}
	
	//get image info 
	$output .=  "&post" . $i . "totalImages=".$post->userImage;
	if($post->userImage > 0){
		$resultImage = mysql_query("SELECT imageLocation, description 
						FROM ".TABLE_PREFIX."_images 
						WHERE postID = $postID");
		
		//check for multiple images
		for($img = 0; $img < $post->userImage; $img++){
			$postImage = mysql_fetch_object($resultImage);
			if($postImage != ""){
				$imageInfo = @getimagesize($abImgDir.$postImage->imageLocation);
				//$message .= "<img src=\"".$installDirectory.$imgDir.$postImage->imageLocation."\" width=\"".$imageInfo[0]."\" height=\"".$imageInfo[1]."\" />";
				$output .= "&post" . $i . "image" . $img . "Location=" . urlencode($webImgDir.$postImage->imageLocation);
				$output .= "&post" . $i . "image" . $img . "Description=" . stripslashes(urlencode($postImage->description));
				$output .= "&post" . $i . "image" . $img . "Width=" . $imageInfo[0];
				$output .= "&post" . $i . "image" . $img . "Height=" . $imageInfo[1];
			}
		}
	}
	
	// Add post details to output
	$output .= "&post" . $i . "postID=" . $postID;
	$output .= "&post" . $i . "author=" . urlencode($username);
	$output .= "&post" . $i . "authorID=" . $userID;
    $output .= "&post" . $i . "date=" . urlencode($posted);
    $output .= "&post" . $i . "userTitle=" . urlencode($userTitle);
    $output .= "&post" . $i . "message=" .  urlencode($message);
	$output .= "&post" . $i . "emoticons=" . urlencode($emoticons);
	$output .= "&post" . $i . "signature=" . urlencode($signature);
	$output .= "&post" . $i . "location=" . urlencode($location);
    $output .= "&post" . $i . "homepage=" . urlencode($homepage);
    $output .= "&post" . $i . "email=" . urlencode($email);
	$output .= "&post" . $i . "avatarURL=" . urlencode($avatarURL);
    $output .= "&post" . $i . "posts=" . urlencode($posts);
	$output .= "&post" . $i . "joined=" . urlencode($joined);
}

// Output all posts in one go
echo $output;

// Build and execute query to update views count for thread
$query = "UPDATE ".TABLE_PREFIX."_threads SET views = views + 1 WHERE threadID = ".$threadID;
// Execute query
$result = @mysql_query($query);

// Close link to database server
mysql_close($link);
?>